using System;

namespace ClassicBehaviorTree
{
    public class ConditionNode : Node, ISetNodeFunction
    {
        private ConditionPattern _pattern;
        private Func<bool> Condition = delegate { return false; };
        private Action ON_Reset = delegate { };
        public ConditionNode() { }
        public ConditionNode(ConditionPattern pattern) { _pattern = pattern; }
        public ConditionNode(string pattern) { _pattern = (ConditionPattern)Enum.Parse(typeof(ConditionPattern), pattern); }
        public void SetNodeFunction(INodeFunction INodeFunction)
        {
            Condition = INodeFunction.Condition;
            ON_Reset += INodeFunction.ResetCondition;
        }
        public override NodeState Update()
        {
            switch (_pattern)
            {
                case ConditionPattern.Watcher:
                    _state = Condition() ? NodeState.Success : NodeState.Failure;
                    break;
                case ConditionPattern.CheckOnce:
                    if (_state == NodeState.Ready)
                    {
                        _state = Condition() ? NodeState.Success : NodeState.Failure;
                    }
                    break;
                case ConditionPattern.PositiveTrigger:
                    if (_state != NodeState.Success)
                    {
                        _state = Condition() ? NodeState.Success : NodeState.Failure;
                    }
                    break;
                case ConditionPattern.NegativeTrigger:
                    if (_state != NodeState.Failure)
                    {
                        _state = Condition() ? NodeState.Success : NodeState.Failure;
                    }
                    break;
                default:
                    throw new Exception("This should never happen, but clearly it has.");
            }
            return _state;
        }
        public override void Reset()
        {
            base.Reset();
            ON_Reset();
        }
    }
}
